/**
 * 厨信通操作函数
 * 基于旧项目的cxtData.js进行迁移和重构
 */

import { LocalStorage } from '@/utils/storage'
import { isEmpty } from '@/utils/toolsValidate'
import { wsLogger } from '@/utils/wsLogger'
import {
    getCXTOrderInfoApi,
    CXTOrderInfoCreateApi,
    CXTBaseAreaBatchCreateApi,
    CXTOrderZhuoTaiDishBatchCreateApi,
    deleteDataApi,
    batchDataCreateApi,
    dataUpdateApi,
    dataBatchUpdateApi,
    getDataListApi
} from './sqlServer'
import {
    fetchCacheDeskList, fetchRegionList
} from '@/api/desktop'
import { fetchfoodCategoryList, fetchCacheFoodList, reportOrderState } from '@/api/food'

import { getNowDateAndTime } from '@/utils/index'
import { getUuid, createordernum } from '@/utils/index'

/**
 *  获取桌台信息
 */
export function getCXTOrderInfo(currentDeskDetail) {
    console.log('当前桌台信息1====>', currentDeskDetail)

    return getCXTOrderInfoApi({ datasource_id: currentDeskDetail.id, OrderStatus: 0 }).then(res => {
        console.log('当前桌台信息2---res====>', res)
        if (!res) {
            return CXTOrderCreate(currentDeskDetail).then(() => {
                return getCXTOrderInfoApi({ datasource_id: currentDeskDetail.id, OrderStatus: 0 }).then(res => {
                    console.log('当前桌台信息3---res====>', res)
                    return res;
                })
            })
        }
        return res;
    })
}

export function getStatusName(status) {
    let name = '';
    switch (status) {
        case 1:
            name = '';
            break;
        case 2:
            name = '催菜';
            break;
        case 3:
            name = '等叫';
            break;
    }
    return name;
}

/**
 * 开台
 * @param {*} currentDeskDetail
 * @returns
 */
export function CXTOrderCreate(currentDeskDetail) {
    const { currentNowDateTime } = getNowDateAndTime()
    const data = {
        UID: getUuid(),
        OrderCode: createordernum(),
        TotalPeopleNum: currentDeskDetail.use_num,
        AddTime: currentNowDateTime,
        UpdateTime: currentNowDateTime,
        datasource_id: currentDeskDetail.id,
    }
    return CXTOrderInfoCreateApi(data).then(res => {
        console.log('开台---res====>', res)
        return res;
    })
}

/**
 * 撤台、结算
 */
export function CXTOrderInfoUpdate(data) {
    const cxtOrderInfo = LocalStorage.getJson('cxtOrderInfo')
    let where = {
        UID: cxtOrderInfo.UID,
    }
    return dataUpdateApi('OrderInfo', where, data)
}

/**
 * 创建菜品订单
 * @param {*} foodList
 */
export async function CXTOrderZhuoTaiDishCreate(orderInfo) {
    const { currentNowDateTime } = getNowDateAndTime()
    let foodData = []
    let foodOrderData = []
    let foodList = orderInfo.foodList
    
    try {
        const cxtOrderInfo = await getCXTOrderInfo({ id: orderInfo.record_id, use_num: 1 })
        console.log('厨信通---cxtOrderInfo====>', cxtOrderInfo)
        
        // 套餐菜品
        foodList.map(item => {
            if (!isEmpty(item.group_info)) {
                item.group_info.map(f => {
                    foodOrderData.push({
                        UID: getUuid(),
                        OrderID: cxtOrderInfo.UID,
                        DishName: f.name,
                        DishTypeName: f.category.name || '',
                        UnitName: f.unit,
                        DishNum: Number(f.num * item.num) || 0,
                        DishPrice: '',
                        WaiterName: orderInfo.clerkName,
                        DishStatusID: 1,
                        AreaName: orderInfo.deskRegion,
                        ZuoFaNames: (isEmpty(f?.making) ? '' : f.making.join(',')) || '',
                        KouWeiNames: ((isEmpty(f?.taste) ? '' : f.taste.join(',')) || '') + ' ' + ((isEmpty(f?.position) ? '' : f.position.join(',')) || ''),
                        ZhuoTaiName: orderInfo.deskName,
                        UpdateTime: currentNowDateTime,
                        AddTime: currentNowDateTime,
                        DishStatusDesc: isEmpty(item?.status) ? '' : (item.status == 3 ? '等叫' : ''),
                        datasource_id: f.id,
                        group_datasource_id: item.id,
                    })

                })
            } else {
                item.making = !isEmpty(item.making) ? item.making : []
                if (item.write_making) {
                    item.write_making.map(makeing => {
                        item.making.push(makeing.name)
                    })
                }
                item.taste = !isEmpty(item.taste) ? item.taste : []
                if (item.write_taste) {
                    item.write_taste.map(taste => {
                        item.taste.push(taste)
                    })
                }
                if (item.is_write_food) {
                    foodData.push({
                        UID: getUuid(),
                        DishName: item.name,
                        UnitName: item.unit
                    })
                }
                foodOrderData.push({
                    UID: getUuid(),
                    OrderID: cxtOrderInfo.UID,
                    DishName: item.name,
                    DishTypeName: item.category.name || '',
                    UnitName: item.unit,
                    DishNum: Number(item.num) || 0,
                    DishPrice: item.money,
                    WaiterName: orderInfo.clerkName,
                    DishStatusID: 1,
                    AreaName: orderInfo.deskRegion,
                    ZuoFaNames: (isEmpty(item.making) ? '' : item.making.join(',')) || '',
                    KouWeiNames: ((isEmpty(item.taste) ? '' : item.taste.join(',')) || '') + ' ' + ((isEmpty(item.position) ? '' : item.position.join(',')) || ''),
                    ZhuoTaiName: orderInfo.deskName,
                    UpdateTime: currentNowDateTime,
                    AddTime: currentNowDateTime,
                    DishStatusDesc: isEmpty(item?.status) ? '' : (item.status == 3 ? '等叫' : ''),
                    datasource_id: item.id,
                    group_datasource_id: ''
                })
            }
        })
        
        console.log('foodData====>', foodData)
        console.log('foodOrderData====>', foodOrderData)
        
        const batchResult = await CXTOrderZhuoTaiDishBatchCreateApi(foodOrderData)
        console.log('cxt_res====>', batchResult)
        
        if (foodData.length > 0) {
            const dishResult = await batchDataCreateApi('BaseDish', foodData)
            return { batchResult, dishResult }
        }
        
        return batchResult
    } catch (error) {
        console.error('创建菜品订单失败:', error)
        throw error
    }
}

/**
 * 同步数据（分区、菜品、菜品分类、桌台）
 */
export async function syncCXTData() {
    try {
        syncCXTBaseArea()
        syncCXTBaseZhuoTai()
        syncCXTBaseDishType()
        orderStateReport() // 已移至心跳处理中，避免重复启动
    } catch (error) {
        return error
    }
}

/**
 * 同步分区
 */
export function syncCXTBaseArea() {
    deleteDataApi('BaseArea').then(() => {
        fetchRegionList({}).then(res => {
            if (res.status === 200 && !isEmpty(res?.data)) {
                const areaData = res.data.map(item => {
                    return {
                        uid: getUuid(),
                        areaName: item.name,
                        code: item.id,
                        datasource_id: item.id,
                    }
                })
                CXTBaseAreaBatchCreateApi(areaData);
            }
        })
        // syncCXTBaseZhuoTai()
    })
}

/**
 * 同步桌台
 */
export function syncCXTBaseZhuoTai() {
    deleteDataApi('BaseZhuoTai').then(() => {
        fetchCacheDeskList({}).then(res => {
            if (res.status === 200 && !isEmpty(res?.data)) {
                const deskData = res.data.map(item => {
                    return {
                        UID: getUuid(),
                        ZTName: item.name,
                        datasource_id: item.id,
                    }
                })
                batchDataCreateApi('BaseZhuoTai', deskData)
            }
        })
        // syncCXTBaseDishType()
    })
}

/**
 * 同步菜品分类
 */
export function syncCXTBaseDishType() {
    deleteDataApi('BaseDishType').then(() => {
        fetchfoodCategoryList({ parent_id: -1 }).then(res => {
            if (res.status === 200 && !isEmpty(res?.data)) {
                let baseDishTypeData = []
                res.data.map(item => {
                    baseDishTypeData.push({
                        UID: getUuid(),
                        TypeName: item.name,
                        TypeCode: item.id,
                        datasource_id: item.id,
                    })
                    if (item.children) {
                        item.children.map(cItem => {
                            baseDishTypeData.push({
                                UID: getUuid(),
                                TypeName: cItem.name,
                                TypeCode: cItem.id,
                                datasource_id: cItem.id,
                            })
                        })
                    }
                })

                batchDataCreateApi('BaseDishType', baseDishTypeData).then(() => {
                    syncCXTBaseDish(baseDishTypeData)
                })
                // syncCXTBaseDish(baseDishTypeData)
            }
        })
    })
}

/**
 * 同步菜品
 * @param {*} baseDishType
 */
export async function syncCXTBaseDish(baseDishType) {
    await deleteDataApi('BaseDish')
    const res = await fetchCacheFoodList({})

    if (res.status === 200 && !isEmpty(res?.data)) {
        const baseDishData = res.data.map(item => {
            let type = baseDishType.find(typeItem => typeItem.datasource_id == item.category_id)
            return {
                UID: getUuid(),
                TypeID: type?.UID || '',
                DishCode: item.id,
                DishName: item.name,
                datasource_id: item.id,
            }
        })

        // 分批处理（每组50条）
        const chunkSize = 50
        for (let i = 0; i < baseDishData.length; i += chunkSize) {
            const chunk = baseDishData.slice(i, i + chunkSize)
            try {
                await batchDataCreateApi('BaseDish', chunk)
            } catch (err) {
                console.error(`处理第 ${i / chunkSize + 1} 批数据时出错:`, err)
            }
        }
    }
}
/**
 *  全部退菜 &批量退菜
 * @param {*} foodData
 */
export async function CXTOrderTuiCaiBatchUpdate(foodDatas) {
    console.log('退菜--->>>', foodDatas)
    const cxtOrderInfo = LocalStorage.getJson('cxtOrderInfo')
    let data = {}
    let where = {}
    let fieldSet = {}
    
    try {
        // 全部退菜
        if (foodDatas.is_all) {
            data = { 'DishNum': 0 }
            where = { OrderID: cxtOrderInfo.UID }
            fieldSet = {
                DishTuiCaiNum: 'DishNum'
            }
            console.log('批量退菜---where data>', where, data)
            return await dataUpdateApi('OrderZhuoTaiDish', where, data)
        } else {// 批量退菜
            let back_list = foodDatas.back_list;
            let batchData = []
            for (let i in back_list) {
                data = {
                    'DishTuiCaiNum': back_list[i].num,
                    'DishNum': Number(back_list[i].food_num),
                }
                where = {
                    datasource_id: back_list[i].id,
                }
                batchData.push({
                    where: where,
                    data: data
                })
            }
            console.log('批量退菜---batchData>', batchData)
            return await dataBatchUpdateApi('OrderZhuoTaiDish', batchData)
        }
    } catch (error) {
        console.error('退菜操作失败:', error)
        throw error
    }
}

/**
 *  退菜
 * @param {*} orderInfo
 */
export async function CXTOrderTuiCaiUpdate(orderInfo) {
    const foodList = orderInfo.foodList
    let batchData = []
    
    try {
        foodList.map(item => {
            let data = {
                DishTuiCaiNum: Number(item.back_num) || 0,
                DishNum: Number(item.num) || 0,
            }
            let where = {
                datasource_id: item.id,
            }
            batchData.push({
                where: where,
                data: data
            })
        })
        console.log('退菜2--批量退菜---batchData>', batchData)
        return await dataBatchUpdateApi('OrderZhuoTaiDish', batchData)
    } catch (error) {
        console.error('退菜操作失败:', error)
        throw error
    }
}

/**
 * 修改菜品订单
 * @param {*} foodData
 */
export async function CXTOrderZhuoTaiDishUpdate(orderInfo) {
    console.log('修改菜品订单cxt_update111', orderInfo)
    const foodList = orderInfo.foodList
    let batchData = []
    console.log('修改菜品订单cxt_update222', foodList)
    
    try {
        foodList.map(item => {
            if (!isEmpty(item.group_info)) {
                let data = {
                    DishStatusDesc: getStatusName(item.status)
                }
                let where = {
                    group_datasource_id: item.id,
                }
                batchData.push({
                    where: where,
                    data: data
                })
            } else {
                let data = {
                    DishStatusDesc: getStatusName(item.status)
                }
                let where = {
                    datasource_id: item.id,
                }
                batchData.push({
                    where: where,
                    data: data
                })
            }
        })
        console.log('修改菜品订单cxt_update333', batchData)
        return await dataBatchUpdateApi('OrderZhuoTaiDish', batchData)
    } catch (error) {
        console.error('修改菜品订单失败:', error)
        throw error
    }
}

/**
 * 批量修改菜品订单
 * @param {*} foodData
 */
export async function CXTOrderZhuoTaiDishBatchUpdate(data) {
    const cxtOrderInfo = LocalStorage.getJson('cxtOrderInfo')
    // 全部退菜
    let where = { OrderID: cxtOrderInfo.UID }
    console.log('批量修改菜品订单-》全部退菜---where, data:', where, data)
    
    try {
        return await dataUpdateApi('OrderZhuoTaiDish', where, data)
    } catch (error) {
        console.error('批量修改菜品订单失败:', error)
        throw error
    }
}

/**
 * 菜品并台
 */
export async function CXTMergeDeskOrder(orderInfo) {
    let newDeskInfo = orderInfo.targetDeskInfo;

    try {
        const cxtOldOrderInfo = await getCXTOrderInfo({ id: orderInfo.record_id, use_num: 0 })
        const cxtNewOrderInfo = await getCXTOrderInfo({ id: orderInfo.target_record_id, use_num: 0 })
        
        let data = {
            ZhuoTaiName: newDeskInfo.name || '',
            AreaName: newDeskInfo.region.name || '',
            OrderID: cxtNewOrderInfo.UID,
        }
        let where = {
            OrderID: cxtOldOrderInfo.UID,
        }
        console.log('菜品并台---where, data:', where, data)
        return await dataUpdateApi('OrderZhuoTaiDish', where, data)
    } catch (error) {
        console.error('菜品并台失败:', error)
        throw error
    }
}

/**
 * 撤台
 */
export async function CXTDeskOrderUpdate(orderInfo) {
    let data = {
        OrderStatus: 1
    }
    let where = {
        datasource_id: orderInfo.record_id,
        OrderStatus: 0
    }
    console.log('撤台---data:', data)
    
    try {
        return await dataUpdateApi('OrderInfo', where, data)
    } catch (error) {
        console.error('撤台失败:', error)
        throw error
    }
}
/**
 * 更新（结算）
 */
export async function CXTDeskOrderbatchUpdate(orderInfo) {
    let batchData = []
    const deskList = orderInfo.deskList
    
    try {
        deskList.map(item => {
            let data = {
                OrderStatus: 1
            }
            let where = {
                datasource_id: item.desk_id,
                OrderStatus: 0
            }
            batchData.push({
                where: where,
                data: data
            })
        })
        console.log('更新（结算）---data:', batchData)
        return await dataBatchUpdateApi('OrderInfo', batchData)
    } catch (error) {
        console.error('批量结算失败:', error)
        throw error
    }
}

/**
 * 转台
 */
export async function CXTChangeDesk(orderInfo) {
    // let oldDeskInfo = orderInfo.deskInfo;
    let newDeskInfo = orderInfo.targetDeskInfo;

    try {
        const cxtOrderInfo = await getCXTOrderInfo({ id: orderInfo.record_id, use_num: 0 })
        let data = {
            ZhuoTaiName: newDeskInfo.name || '',
            AreaName: newDeskInfo.region.name || ''
        }
        let where = {
            OrderID: cxtOrderInfo.UID,
        }
        console.log('转台---data:', data)
        return await dataUpdateApi('OrderZhuoTaiDish', where, data)
    } catch (error) {
        console.error('转台失败:', error)
        throw error
    }
}


// 全局定时器引用，用于清理
let orderReportTimer: NodeJS.Timeout | null = null

export function orderStateReport() {
    wsLogger.info('CXT', '启动订单状态报告定时器', { interval: '5秒' })
    
    // 清理之前的定时器
    if (orderReportTimer) {
        clearInterval(orderReportTimer)
        wsLogger.debug('CXT', '清理之前的订单状态报告定时器')
    }

    orderReportTimer = setInterval(() => {
        wsLogger.debug('CXT', '执行订单状态报告检查')
        
        // 获取已制作未上报的数据
        getDataListApi('CXT_DishesInfor', { cxt_state: 4, is_report: 0 }, ['ItemID']).then(dishesList => {
            if (dishesList && dishesList.length > 0) {
                wsLogger.info('CXT', `发现 ${dishesList.length} 条已制作未上报的菜品`, { count: dishesList.length })
                
                let uids = []
                for (let i in dishesList) {
                    uids.push(dishesList[i].ItemID)
                }
                let value = "('" + uids.join("','") + "')"
                console.log("CXT_DishesInfor", value)
                
                getDataListApi('OrderZhuoTaiDish', { UID: { type: 'in', value: value } }, ['datasource_id']).then(orderList => {
                    console.log("CXT_DishesInfor", orderList)
                    if (orderList && orderList.length > 0) {
                        let orderIds = orderList.map(order => order.datasource_id)
                        wsLogger.info('CXT', `开始上报 ${orderIds.length} 个订单状态`, { orderIds })
                        
                        reportOrderState({ ids: orderIds }).then(res => {
                            wsLogger.info('CXT', '订单状态上报完成', { orderCount: orderIds.length, result: res })
                            
                            dataUpdateApi('CXT_DishesInfor', { ItemID: { type: 'in', value: value } }, { is_report: 1 }).then(res1 => {
                                wsLogger.debug('CXT', '更新菜品上报状态完成', { updatedCount: dishesList.length })
                            }).catch(error => {
                                wsLogger.error('CXT', '更新菜品上报状态失败', error)
                            })
                        }).catch(error => {
                            wsLogger.error('CXT', '订单状态上报失败', error)
                        })
                    } else {
                        wsLogger.debug('CXT', '未找到对应的订单数据')
                    }
                }).catch(error => {
                    wsLogger.error('CXT', '查询订单数据失败', error)
                })
            } else {
                wsLogger.debug('CXT', '暂无已制作未上报的菜品')
            }
        }).catch(error => {
            wsLogger.error('CXT', '订单状态报告数据库查询失败', error)
        })
    }, 5000); // 改为10秒间隔，避免与心跳冲突
}

/**
 * 清理订单状态报告定时器
 */
export function clearOrderStateReport() {
    if (orderReportTimer) {
        clearInterval(orderReportTimer)
        orderReportTimer = null
        wsLogger.info('CXT', '订单状态报告定时器已清理')
        console.log('订单状态报告定时器已清理')
    } else {
        wsLogger.debug('CXT', '订单状态报告定时器不存在，无需清理')
    }
}






/**
 * 处理WebSocket厨信通消息
 * @param messageData 厨信通消息数据
 */
export async function handleCXTMessage(messageData: any): Promise<any> {
    try {
        wsLogger.info('CXT', `处理厨信通消息 - 类型: ${messageData.type}`, { messageType: messageData.type, messageData })
        console.log('厨信通模块处理消息:', messageData)

        // 厨信通消息类型处理映射
        const CXT_MESSAGE_HANDLERS: Record<string, (detail: any) => Promise<any>> = {
            'QC': async (detail: any) => {
                // 起菜单 - 更新桌台菜品状态 之前判断了ID 我看没有返回ID 先不判断
                // if (detail.id) {
                return await CXTOrderZhuoTaiDishUpdate(detail)
                // }
            },
            'DC': async (detail: any) => {
                // 点菜单 - 创建桌台菜品订单
                return await CXTOrderZhuoTaiDishCreate(detail)
            },
            'DJ': async (detail: any) => {
                // 等叫单 - 更新菜品等待状态
                return await CXTOrderZhuoTaiDishUpdate(detail)
            },
            'CC': async (detail: any) => {
                // 催菜单 - 催促菜品制作
                return await CXTOrderZhuoTaiDishUpdate(detail)
            },
            'TC': async (detail: any) => {
                // 退菜单 - 处理菜品退菜
                return await CXTOrderTuiCaiUpdate(detail)
            },
            'BG': async (detail: any) => {
                // 数量变更单 - 菜品数量调整
                console.log('数量变更单处理:', detail)
                return { status: 200, message: '数量变更单处理完成', data: detail }
            },
            'YJ': async (detail: any) => {
                // 预结单 - 预结算处理
                console.log('预结单处理:', detail)
                return { status: 200, message: '预结单处理完成', data: detail }
            },
            'JZ': async (detail: any) => {
                // 结账单 - 批量更新桌台订单
                return await CXTDeskOrderbatchUpdate(detail)
            },
            'HC': async (detail: any) => {
                // 划菜总单[全单重打]
                console.log('划菜总单处理:', detail)
                return { status: 200, message: '划菜总单处理完成', data: detail }
            },
            'CD': async (detail: any) => {
                // 重打菜品单【单菜重打】
                console.log('重打菜品单处理:', detail)
                return { status: 200, message: '重打菜品单处理完成', data: detail }
            },
            'ZT': async (detail: any) => {
                // 转台通知单 - 桌台转移
                return await CXTChangeDesk(detail)
            },
            'CT': async (detail: any) => {
                // 桌台变更 - 更新桌台信息
                return await CXTDeskOrderUpdate(detail)
            },
            'BT': async (detail: any) => {
                // 并台操作 - 合并桌台订单
                return await CXTMergeDeskOrder(detail)
            },
            'CZT': async (detail: any) => {
                // 菜品转台通知单
                console.log('菜品转台通知单处理:', detail)
                return { status: 200, message: '菜品转台通知单处理完成', data: detail }
            },
            'YD': async (detail: any) => {
                // 预订单 - 预订处理
                console.log('预订单处理:', detail)
                return { status: 200, message: '预订单处理完成', data: detail }
            }
        }

        const handler = CXT_MESSAGE_HANDLERS[messageData.type]
        if (handler) {
            const result = await handler(messageData.detail)
            console.log(`厨信通消息 ${messageData.type} 处理完成，结果:`, result)
            return result
        } else {
            console.warn('未知的厨信通消息类型:', messageData.type)
            return { status: 400, message: `未知的消息类型: ${messageData.type}`, data: null }
        }
    } catch (error) {
        wsLogger.error('CXT', '厨信通模块处理消息失败', error, { messageData })
        console.error('厨信通模块处理消息失败:', error)
        throw error
    }
}
